from cgi import parse_qs, escape
import os
#Wrap math equation into Online Latex form
def wrap_math(math) :
   math = '<img src="http://latex.codecogs.com/gif.latex?' + math
   math = math + '" />'
   math = math.replace('\\exponent', '^')
   return math

# wrap search location string
def wrap_search_location (str) :
   str = '<p style="color:blue;font-style:italic;size:20px;">' + str
   str = str + '</p>'
   return str

def application( # It accepts two arguments:
      # environ points to a dictionary containing CGI like environment variables
      # which is filled by the server for each received request from the client
      environ,
      # start_response is a callback function supplied by the server
      # which will be used to send the HTTP status and headers to the server
      start_response):

    # get a query from the webpage :)
   try:
      request_body_size = int(environ.get('CONTENT_LENGTH', 0))
   except (ValueError):
      request_body_size = 0

   request_body = environ['wsgi.input'].read(request_body_size)
   data = parse_qs(request_body)

   query = data.get('query', [''])[0]

   argument = "python D:\\wsgi_app\\process_search.py " + query
   os.system(argument)

   html = '''
   <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
   <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" >
       <head>
           <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
           <title>Search Results</title>
       </head>
       
       <body>
           You searched for: $(SEARCH_TERMS_GO_HERE)
           <br /><br />
           Search Results:
           $(SEARCH_RESULTS_GO_HERE)
       </body>
   </html>
   '''
   html = html.replace('$(SEARCH_TERMS_GO_HERE)', wrap_search_location(query) + wrap_math(query)) # output query

   RESULT = open("D:\\equation_search\\server\\result", "r")

   search_location = [] # Where the each formulas are
   search_result = ""
   search_math = [] # shows the each math formula

   lines = RESULT.readlines()
   line = ""
   
   cnt = 0
   for line in lines:
      if cnt % 2 == 0 :
         search_location.append(wrap_search_location(line.strip('\n')))
      else :
         search_math.append(wrap_math(line.strip('\n')))
      cnt = cnt + 1

   RESULT.close()
   for i in range(0, len(search_location)):
      search_result = search_result + search_location[i] + search_math[i] + '</br></br>'
      
   html = html.replace('$(SEARCH_RESULTS_GO_HERE)', search_result)

   # build the response body possibly using the environ dictionary
   response_body = html
   # HTTP response code and message
   status = '200 OK'

   # These are HTTP headers expected by the client.
   # They must be wrapped as a list of tupled pairs:
   # [(Header name, Header value)].
   response_headers = [('Content-Type', 'text/html'),
                       ('Content-Length', str(len(response_body)))]

   # Send them to the server using the supplied function
   start_response(status, response_headers)

   # Return the response body.
   # Notice it is wrapped in a list although it could be any iterable.
   return [response_body]